package com.tgky.ybzb.config.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tgky.ybzb.config.exception.YBGLBaesException;
import com.tgky.ybzb.entity.SysUser;
import org.apache.commons.lang.StringUtils;

import java.util.Calendar;

public class JwtUtil {
    /**
     * 盐值
     */
    private static final String SING = "tgky";

    /**
     * 获取token
     *
     * @param user
     * @return
     */
    public static String getToken(SysUser user) {
        Calendar instance = Calendar.getInstance();
        //令牌过期时间
        instance.add(Calendar.DATE, 1);
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("userId", user.getUserId())
                .withClaim("userName", user.getUsername());
        return builder.withExpiresAt(
                instance.getTime()).sign(Algorithm.HMAC256(SING));
    }

    /**
     * 验证token合法性 成功返回token
     *
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) throws YBGLBaesException {
        if (StringUtils.isEmpty(token)) {
            throw new YBGLBaesException(501, "token为空");
        }
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SING)).build();
        return build.verify(token);
    }

    /**
     * 获取token中的用户信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

}